# coding=utf-8

import numpy as np
import pandas as pd
from sklearn.utils import shuffle


class AdalineGD(object):

    def __init__(self, eta=0.01, n_iter=50):
        self.eta = eta
        self.n_iter = n_iter

    def fit(self, X, y):
        self.w_ = np.zeros(1 + X.shape[1])
        self.cost_ = []
        for i in range(self.n_iter):
            output = self.net_input(X)
            errors = (y - output)
            self.w_[1:] += self.eta * X.T.dot(errors)
            self.w_[0] += self.eta * errors.sum()
            cost = (errors**2).sum() / 2.0
            self.cost_.append(cost)
        return self

    def net_input(self, X):
        return np.dot(X, self.w_[1:])

    def activation(self, X):
        return self.net_input(X)

    def predict(self, X):
        return np.where(self.activation(X) >= 0.0, 1, -1)

df = pd.read_csv(
    'iris.data.txt', header=None)
df = shuffle(df)
y2 = df.iloc[100:, 4].values
y2 = np.where(y2 == 'Iris-setosa', -1, 1)
print y2
print "#########################"
y = df.iloc[:100, 4].values
y = np.where(y == 'Iris-setosa', -1, 1)
X = df.iloc[:100, :3].values


df = pd.read_csv(
    'iris.data.txt', header=None)

right = 0.0
count = 0
for _ in xrange(1000000):
    df = shuffle(df)
    y2 = df.iloc[100:, 4].values
    y2 = np.where(y2 == 'Iris-setosa', -1, 1)
    # print y2
    # print "#########################"
    y = df.iloc[:100, 4].values
    y = np.where(y == 'Iris-setosa', -1, 1)
    X = df.iloc[:100, :3].values

    ppn = AdalineGD(eta=0.0001, n_iter=50)
    ppn.fit(X, y)
    i = 0
    for x in df.iloc[100:, :3].values:
        if ppn.predict(x) == y2[i]:
            right += 1
        i += 1
        count += 1
    print '正确率：', right / count
